import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import router from '@/router'
import {removeAccount} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 9999) {
      removeAccount()
      router.push('/login')
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    if (res.code !== 1) {
      Message({
        message: res.msg || '服务器出现错误！',
        type: 'error',
        duration: 4000
      });
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export default service
